# coding=utf-8
import hashlib, requests,random,string,json
from application import  app
import base64
import json
from Crypto.Cipher import AES

class CustomerLibs():
    @staticmethod
    def geneAuthCode( customer_info = None ):
        m = hashlib.md5()
        str = "%s-%s" % ( customer_info.id, customer_info.salt)
        m.update(str.encode("utf-8"))
        return m.hexdigest()

    @staticmethod
    def geneSalt( length = 16 ):
        keylist = [ random.choice( ( string.ascii_letters + string.digits ) ) for i in range( length ) ]
        return ( "".join( keylist ) )

    @staticmethod
    def getWeChatOpenIdAndSessionKey( code ):
        url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" \
            .format(app.config['MINA_APP']['appid'], app.config['MINA_APP']['appkey'], code)
        r = requests.get(url)
        res = json.loads(r.text)
        if "errcode" not in res :
            openid = res['openid']
            session_key = res["session_key"]
            return { "open_id" : openid, "session_key" : session_key }
        else :
            return {}

    @staticmethod
    def getMobile(session_key, encrypted_data, iv):
        app_id = app.config['MINA_APP']['appid']
        # base64 decode
        sessionKey = base64.b64decode(session_key)
        encryptedData = base64.b64decode(encrypted_data)
        iv = base64.b64decode(iv)

        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)

        unpad = cipher.decrypt(encryptedData)
        unpad = unpad[:-ord(unpad[len(unpad) - 1:])]
        decrypted = json.loads(unpad)

        if decrypted['watermark']['appid'] != app_id:
            return None
        return decrypted["purePhoneNumber"]